//
//  GSSubscribeViewController_Add_Topic.m
//  GameSky
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSSearchViewController.h"
#import "GSSubscribeViewController_Add_Topic.h"
#import "GSSubscribeViewController_Add_Topic_Details.h"
#import "GSSubscribeViewController_Add_Topic_Cell.h"
#import "GSSubscrebe_Add_Topic.h"
#import "GSBorderButton.h"
@interface GSSubscribeViewController_Add_Topic () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
// 展示页面
@property (nonatomic, strong) UITableView *tableView;
// 判断 滑动的点坐标
@property (nonatomic, assign) NSInteger y;
// 数据源数组
@property (nonatomic, strong) NSMutableArray *dataArray;
// 请求参数 字典
@property (nonatomic, strong) NSDictionary *dic;
/**
 * 数据库
 */
@property (nonatomic, strong) FMDatabase *db;
// 获取数据库中的数据
@property (nonatomic, strong) NSMutableArray *dbArray;
@end

@implementation GSSubscribeViewController_Add_Topic

#pragma mark-------------视图加载完成-------------------
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
// 初始化 数据源数组
    self.dataArray = [NSMutableArray array];
//  解析数据库数据
    [self getDataArrayByDB];
// 添加tableView
    [self addTableView];
// 解析数据
    [self setUpData];
    
}

#pragma mark------------解析数据-----------------------
- (void)setUpData{
    _dic = @{@"request":@{@"type":self.typeNumber}};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/subscribe" paraDict:_dic method:POST success:^(NSURLResponse *response, NSData *data) {

        NSMutableDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        // 获取所需数据
        NSArray *array = dicData[@"result"];
        // 遍历, 给 model赋值
        for (NSDictionary *oneDic in array) {
            GSSubscrebe_Add_Topic *model = [[GSSubscrebe_Add_Topic alloc] init];
            // 赋值
            [model setValuesForKeysWithDictionary:oneDic];
            // 数据源数据装载 model
            [_dataArray addObject:model];
        }
        // 刷新界面
        _tableView.tableFooterView.hidden = NO;
        [_tableView reloadData];
        
        
    } failure:^(NSError *error) {
          NSLog(@"请求出错");
    }];
    
}
#pragma mark-------------数据库数组懒加载-------------
- (NSMutableArray *)dbArray{
    if (!_dbArray) {
        _dbArray = [NSMutableArray array];
    }
    return _dbArray;
}
#pragma mark-------------从数据库中提取数据-----------
- (void)getDataArrayByDB{
    // 从数据库里获取 数据
    // 打开数据库
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    // 拼接路径
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    // 清空数组
    [self.dbArray removeAllObjects];
    
    FMResultSet *resultSet = [_db executeQuery:@"select * from SubscribeList"];
    while ([resultSet next]) {
        NSString *nodeIds = [resultSet stringForColumn:@"nodeIds"];
        NSNumber *cnt = [NSNumber numberWithInt:[resultSet intForColumn:@"cnt"]];
        NSString *sourceName = [resultSet stringForColumn:@"sourceName"];
        NSData *imageData = [resultSet dataForColumn:@"imageData"];
        GSSubscrebe_Add_Topic *model = [[GSSubscrebe_Add_Topic alloc] init];
        model.sourceName = sourceName;
        model.imageModel = [UIImage imageWithData:imageData];
        model.sourceId = nodeIds;
        model.cnt = cnt;
        [self.dbArray addObject:model];
    }
}

#pragma mark-------------添加tableView----------------
- (void)addTableView{
// 创建
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -42, kScreenWidth, kScreenHeight - 64 + 42) style:(UITableViewStylePlain)];
    // 夜间模式
    _tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
// 代理
    _tableView.dataSource = self;
    _tableView.delegate = self;
// 设置行高
    _tableView.rowHeight = 72;
// 添加视图
    [self.view addSubview:_tableView];
// 添加 搜索框
    UIView *search = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 42)];
    UIButton *searchBtn = [GSBorderButton buttonWithType:(UIButtonTypeCustom)];
    searchBtn.frame = CGRectMake(10, (42 - 30) / 2,kScreenWidth - 20, 30);
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchBtn setTitle:@"搜索" forState:(UIControlStateNormal)];
    [searchBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    [searchBtn setImage:[UIImage imageNamed:@"common_Icon_Search_20x20_UIMode_Day"] forState:(UIControlStateNormal)];
    searchBtn.userInteractionEnabled = NO;
    [search addSubview:searchBtn];
// 搜索框  添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [search addGestureRecognizer:tap];
    
    _tableView.tableHeaderView = search;

// 添加 表尾
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,kScreenWidth, 48)];
    footerView.backgroundColor = [UIColor grayColor];
    UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(6, 6, kScreenWidth - 12, 36)];
    footLabel.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:footLabel];
    footLabel.textColor = [UIColor redColor];
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.text = @"没有更多内容了";
    _tableView.tableFooterView = footerView;
    _tableView.tableFooterView.hidden = YES;

    
}

#pragma mark---------------搜索框跳转-------------------
- (void)tap:(UITapGestureRecognizer *)tap{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION" object:nil userInfo:nil];
}
#pragma mark---------------tableView协议方法------------
// 返回多少分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
// 每个分区多少行Cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
// 创建Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// 遍历数据库数据,如果 与请求出来的数据想匹配,则说明 已经被收藏过,则 将model的isSubscribe属性置为yes
    
    // 获取model
    GSSubscrebe_Add_Topic *model = _dataArray[indexPath.row];
    // 初始化 订阅状态
    model.isSubscribe = NO;
    NSString *sourceIdString = [NSString stringWithFormat:@"%@",model.sourceId];
    for (GSSubscrebe_Add_Topic *modelDB in _dbArray) {
        if ([sourceIdString isEqualToString:modelDB.sourceId]) {
            model.isSubscribe = YES;
        }
    }
    
    static NSString *idenfier = @"Cell";
    GSSubscribeViewController_Add_Topic_Cell *cell = [tableView dequeueReusableCellWithIdentifier:idenfier];
    if (cell == nil) {
        cell = [[GSSubscribeViewController_Add_Topic_Cell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:idenfier];
    }
    // 设置选中的样式
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 给订阅按钮 添加 tag  ,通过按钮的tag, 获取 到 对应的model, 保存到数据库
    cell.subscibeButton.tag = indexPath.row;
    // 订阅按钮 添加 方法
    [cell.subscibeButton addTarget:self action:@selector(subscibeButtonAciton:) forControlEvents:(UIControlEventTouchUpInside)];
  
    // 给Cell赋值
    cell.model = model;
    return cell;
}
// cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// 获取model
    GSSubscrebe_Add_Topic *model = _dataArray[indexPath.row];
    
// 创建 请求字典, 添加 相应键值对, 传给下一个界面,方便 请求数据
    NSDictionary *dic = @{@"request":@{@"parentNodeId":@"dingYue",
                                       @"nodeIds":model.sourceId,
                                       @"type":@"dingyueList",
                                       @"pageIndex":@1,
                                       @"elementsCountPerPage":@20}
                          };
    // 获取 图片数据
    GSSubscribeViewController_Add_Topic_Cell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    NSData *imageData = UIImagePNGRepresentation(cell.imageV.image);
    
    NSLog(@"%d",model.isSubscribe);
// 调用 block
    self.block(dic,model.isSubscribe,model,imageData);
}
#pragma mark---------------订阅按钮,实现添加(移除)到数据库-----------
- (void)subscibeButtonAciton:(UIButton *)button{
    // 点击后状态 取反
    button.selected = !button.selected;
    
    // 判断状态,选择背景颜色,并确实 是移除还是 添加到数据库
// 打开数据库
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    // 拼接路径
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    // 获取要插入数据库的数据
    GSSubscrebe_Add_Topic *model = _dataArray[button.tag];
    model.isSubscribe = !model.isSubscribe;
    
    if (button.selected) {
        button.backgroundColor = [UIColor grayColor];
        // 选中状态,则 添加到 数据库
// 获取 图片数据
        GSSubscribeViewController_Add_Topic_Cell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];
        NSData *imageData = UIImagePNGRepresentation(cell.imageV.image);
        if ([_db executeUpdate:@"insert into SubscribeList(nodeIds,cnt,sourceName,imageData) values(?,?,?,?)",model.sourceId,model.cnt,model.sourceName,imageData]) {
            NSLog(@"插入数据成功");
        }else{
            NSLog(@"插入数据失败");
        }
    }else{
        button.backgroundColor = [UIColor redColor];
        // 非选中, 从数据库移除
        
        if (![_db executeUpdate:@"delete from SubscribeList where nodeIds = ?",model.sourceId]) {
            NSLog(@"删除数据失败");
        
        }
    }
}
#pragma mark------------------scrollView协议方法------------
// 实现  显隐  搜索框
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // 保存 拖拽时的点
    self.y = scrollView.contentOffset.y;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    // 利用保存的 点,  判断  滑动方法
    if (scrollView.contentOffset.y > _y) {
        // 上滑
        if (scrollView.contentOffset.y < 0) {
            // 若搜索框仍然  显示,将之 还原 (隐藏)
            [UIView beginAnimations:nil context:nil];
            [scrollView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            [UIView commitAnimations];
        }
    }else{
        // 下滑
        if (scrollView.contentOffset.y < -10) {
            // 若 当前 点,滑动 幅度  大于  10,则 显示 搜索框
            [UIView beginAnimations:nil context:nil];
            [scrollView setContentInset:UIEdgeInsetsMake(42, 0, 0, 0)];
            [UIView commitAnimations];
        }else if (scrollView.contentOffset.y > -10 && scrollView.contentOffset.y < 0)
        {
            // 若 当前 滑动 幅度   小于10 ,则 继续 隐藏 搜索框
            [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    }
}
#pragma mark------------改变订阅按钮的状态--------------
- (void)changeSubscribe{
    // 获取 数据库中的数据
    [self getDataArrayByDB];
    [_tableView reloadData];
}
#pragma mark------------------------------------------
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
